﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

using Seven.Entity;
using Seven.DataModel.RepositoryModels.RoleAbout;
using Seven.DataModel.ViewModels.RoleAbout;
using Seven.Tools.Extension;
using Seven.Tools.Helper;

namespace Seven.Service.Powerful
{
    public partial class SysRoleMenuPermissionService
    {
        #region 提供json数据

        /// <summary>
        /// 获取角色菜单权限数据
        /// </summary>
        /// <param name="roleId">角色ID</param>
        /// <param name="rangeFilter">是否根据管理范围过滤</param>
        /// <returns></returns>
        public JsonResult RoleMenuPermissionGrid(int roleId, bool rangeFilter)
        {
            IEnumerable<SysMenu> range;
            IEnumerable<int> menuIds;
            if (rangeFilter)
            {
                range = CurrentUserMenuRange;
            }
            else
            {
                using (var unit = DbFactory.UnitOfWork)
                {
                    var menuRep = unit.SysMenu;
                    range = menuRep.GetAllMenus();
                }
            }
            if (range.Count() > 0)
            {
                range = range.OrderBy(o => o.SortNumber);
                menuIds = range.Where(w => !string.IsNullOrWhiteSpace(w.ControllerName) && !string.IsNullOrWhiteSpace(w.ActionName)).Select(s => s.ID);
            }
            else { return new DataResult(new List<object>()).SerializeToJsonResult(); }
            using (var unit = DbFactory.UnitOfWork)
            {
                var rep = unit.SysRoleMenuPermission;
                var data = rep.RoleMenuPermissionGrid(roleId, menuIds, true).ToList();
                var otherData = this.GetCurrentMenuPermissionRangeByMenuIDs(menuIds);
                var tempIds = data.Select(s => s.MenuPermissionID);
                //组建无角色权限记录的默认角色权限数据
                foreach (var item in otherData.Where(w => !tempIds.Contains(w.ID)))
                {
                    data.Add(new RoleMenuPermissionGridModel
                    {
                        RoleID = roleId,
                        MenuPermissionID = item.ID,
                        MenuPermissionName = item.Name,
                        MenuPermissionSortNumber = item.SortNumber,
                        MenuID = item.MenuID,
                        Check = false
                    });
                }
                data = data.TryOrderBy(o => o.MenuPermissionSortNumber).ToList();

                return new DataResult(range.Select(s => new
                {
                    s.ID,
                    s.Name,
                    iconCls = string.IsNullOrWhiteSpace(s.IconCls) ? SiteCore.DefaultIconClassName : s.IconCls,
                    s.ParentID,
                    Permissions = data.Where(w => w.MenuID == s.ID).Select(ss => new { ss.MenuPermissionID, ss.MenuPermissionName, State = ss.Check ? 1 : 0 })
                })).SerializeToJsonResult();
            }
        }

        public IEnumerable<SysMenuPermission> GetCurrentMenuPermissionRangeByMenuIDs(IEnumerable<int> menuIds)
        {
            if (menuIds.Count() == 0) { return Enumerable.Empty<SysMenuPermission>(); }
            var range = CurrentUserMenuPermissionRange;
            return range.Where(w => menuIds.Contains(w.MenuID));
        }

        #endregion

        #region CUD操作

        /// <summary>
        /// 保存角色权限
        /// </summary>
        /// <param name="models">权限数据模型</param>
        /// <param name="roleId">角色ID</param>
        /// <param name="otherRoleIds">应用到其他角色ids</param>
        /// <returns></returns>
        public JsonResult SaveRolePermission(IEnumerable<PermissionModel> models, int roleId, string otherRoleIds)
        {
            using (var unit = DbFactory.UnitOfWork)
            {
                #region 角色权限组装

                var rep = unit.SysRoleMenuPermission;
                var oldPermission = rep.GetRoleMenuPermissions(roleId);

                IList<SysRoleMenuPermission> inserts = new List<SysRoleMenuPermission>();
                IList<SysRoleMenuPermission> updates = new List<SysRoleMenuPermission>();
                foreach (var model in models)
                {
                    var temp = oldPermission.FirstOrDefault(f => f.MenuPermissionID == model.MenuPermissionID);
                    if (temp == null)
                    {
                        inserts.Add(new SysRoleMenuPermission { RoleID = roleId, MenuPermissionID = model.MenuPermissionID, Check = model.Check });
                    }
                    else
                    {
                        temp.Check = model.Check;
                        updates.Add(temp);
                    }
                }

                #endregion

                try
                {
                    unit.BeginTransaction();
                    if (inserts.Count() > 0) { rep.EntitiesAdded(inserts); }
                    if (updates.Count() > 0) { rep.EntitiesModified(updates); }
                    var msg = new string[] { "更新成功!", "更新失败!" };
                    return new OperationResult(unit.Commit() > 0, msg).SerializeToJsonResult();
                }
                catch (DataAccessException ex)
                {
                    unit.Rollback();
                    throw ExceptionHelper.ThrowServiceException(ex.Message);
                }
            }
        }

        #endregion
    }
}
